#include "pcap-udp.h"
#include "appender.h"
#include <QDebug>

CPCapUdpSegment::CPCapUdpSegment(QObject *parent) :
    CPCapPacket(parent)
{

}

CPCapUdpSegment::~CPCapUdpSegment()
{

}

QString CPCapUdpSegment::sourcePort() const
{
    return m_sourcePort;
}

void CPCapUdpSegment::setSourcePort(const QString &sourcePort)
{
    m_sourcePort = sourcePort;
    emit sourcePortChanged();
}

QString CPCapUdpSegment::destPort() const
{
    return m_destPort;
}

void CPCapUdpSegment::setDestPort(const QString &destPort)
{
    m_destPort = destPort;
    emit destPortChanged();
}

int CPCapUdpSegment::headerLength()
{
    return 8;
}

bool CPCapUdpSegment::buildHeader(QByteArray &header)
{
    CAppender apd(&header);
    //sourse port (16 bits)
    if (!apd.appendUInt16(m_sourcePort)) {
        qCritical() << "UDP: append src port failed: " << m_sourcePort;
        return false;
    }
    //destination port (16 bits)
    if (!apd.appendUInt16(m_destPort)) {
        qCritical() << "UDP: append dst port failed: " << m_destPort;
        return false;
    }
    //total length (16 bits)
    quint16 length = 8 + payloadLength();
    if (!apd.appendUInt16(length)) {
        qCritical() << "UDP: append length failed";
        return false;
    }
    //checksum (16 bits)
    quint16 checksum = 0;
    if (!apd.appendUInt16(checksum)) {
        qCritical() << "UDP: append checksum failed";
        return false;
    }
    return true;
}
